package com.mju.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mju.controller.common.BaseController;
import com.mju.controller.common.JsonResult;
import com.mju.pojo.Order;
import com.mju.service.IOrderService;
import com.mju.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("orders")
public class OrderController extends BaseController {
    @Autowired
    private IOrderService orderService;


    // 创建订单
    @RequestMapping("createOrder")
    public JsonResult<Order> createOrder(Integer aid, Integer[] cids, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Map<String, String> map = parseTokenGetUidAndUname(token);
        String uid = map.get("uid");
        String uname = map.get("uname");
        Order data = orderService.createOrder(aid, cids, Integer.valueOf(uid), uname);
        return new JsonResult<>(OK, data);
    }

    // 创建订单项
    @PostMapping("/createOrderItem")
    public JsonResult<Void> createOrderItem(Integer oid,Integer cid,Integer num,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Map<String, String> map = parseTokenGetUidAndUname(token);
        String uname = map.get("uname");

        //调用业务层方法执行插入操作
        orderService.createOrderItem(oid,cid,num,uname);
        return new JsonResult<>(OK);
    }

    //处理根据oid查询订单的请求
    @GetMapping("/queryOrderVoByOid")
    public JsonResult<List<OrderVo>>  queryOrderVoByOid(Integer oid){
        List<OrderVo> orderVos = orderService.queryOrderVoByOid(oid);
        return new JsonResult<>(OK,orderVos);
    }


    @GetMapping("/queryOrderVoByUid")
    public JsonResult<List<OrderVo>>  queryOrderVoByUid(Integer uid){
        List<OrderVo> orderVos = orderService.queryOrderVoByUid(uid);
        return new JsonResult<>(OK,orderVos);
    }

    //无条件查询所有订单信息
    @GetMapping("/{currentPage}/{pageSize}")
    public JsonResult<IPage<Order>> queryAllOderInfo(
            @PathVariable("currentPage") Integer currentPage, @PathVariable("pageSize") Integer pageSize){
        IPage<Order> data = orderService.queryAllOrderInfo(currentPage, pageSize);
        return new JsonResult<>(OK,data);
    }

    //条件查询所有订单信息
    @PostMapping("/conQueryAllOderInfo")
    public JsonResult<IPage<Order>> conQueryAllOrderInfo(
            @RequestParam("currentPage") Integer currentPage, @RequestParam("pageSize") Integer pageSize,@RequestBody Order order){
        IPage<Order> data = orderService.conQueryAllOrderInfo(currentPage, pageSize,order);
        //如果当前页码值大于了总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if( currentPage > data.getPages()){
            data = orderService.conQueryAllOrderInfo((int)data.getPages(), pageSize,order);
        }
        return new JsonResult<>(OK,data);
    }
}
